import { mergeDefaultInLeft } from '@ibiz-template/core';
import {
  FormNotifyState,
  ISearchFormController,
  ISearchFormEvent,
  ISearchFormState,
} from '@ibiz-template/runtime';
import { IDESearchForm } from '@ibiz/model-core';
import { FormController } from '../form/form.controller';
import { SearchFormService } from './search-form.service';

/**
 * 搜索表单控制器
 *
 * @author lxm
 * @date 2023-05-15 09:33:27
 * @export
 * @class SearchFormController
 * @extends {FormController<IDESearchForm>}
 * @implements {ISearchFormController}
 */
export class SearchFormController
  extends FormController<IDESearchForm, ISearchFormState, ISearchFormEvent>
  implements ISearchFormController
{
  /**
   * 搜索表单部件服务
   *
   * @author lxm
   * @date 2022-08-19 13:08:51
   * @type {EntityService}
   */
  service!: SearchFormService;

  protected async onCreated(): Promise<void> {
    await super.onCreated();
    // 实例部件服务
    this.service = new SearchFormService(this.model);
    await this.service.init(this.context);
    // 先加载数据，加载完后才会mounted
    await this.load();
  }

  /**
   * 加载草稿
   *
   * @author lxm
   * @date 2022-09-22 17:09:04
   * @returns {*}  {Promise<IData>}
   */
  async load(): Promise<IData> {
    const queryParams = { ...this.params };

    // 新建默认值给到graft接口，接口会回来
    const params = await this.getDraftParams();
    Object.assign(queryParams, params);

    const res = await this.service.getDraft(this.context, queryParams);
    this.state.data = res.data;
    mergeDefaultInLeft(this.data, params);
    this.state.isLoaded = true;
    this.formStateNotify(FormNotifyState.DRAFT);
    return this.data;
  }

  /**
   * 获取搜索表单的视图过滤参数
   *
   * @author lxm
   * @date 2022-09-22 17:09:21
   * @returns {*}  {IParams}
   */
  getParams(): IParams {
    return { ...this.data.getOrigin() };
  }

  /**
   * 执行搜索行为
   * @author lxm
   * @date 2023-03-26 02:27:23
   * @return {*}  {Promise<void>}
   */
  async search(): Promise<void> {
    await this.evt.emit('onSearch', undefined);
  }

  /**
   * 搜索表单按钮回调
   *
   * @author lxm
   * @date 2022-09-22 19:09:07
   */
  async onSearchButtonClick(): Promise<void> {
    await this.search();
  }

  /**
   * 重置搜索表单
   *
   * @author lxm
   * @date 2022-09-22 19:09:07
   */
  async reset(): Promise<void> {
    await this.load();
    await this.search();
  }

  /**
   * 通知所有表单成员表单操作过程中的数据变更
   *
   * @author lxm
   * @date 2022-09-20 18:09:40
   * @param {string[]} names
   */
  async dataChangeNotify(names: string[]): Promise<void> {
    await super.dataChangeNotify(names);
    if (this.model.enableAutoSearch) {
      this.search();
    }
  }

  /**
   * 监听回车事件
   * @param {IData} event
   * @return {*}
   * @author: zhujiamin
   * @date 2022-09-27 16:48:47
   */
  async onKeyUp(event: KeyboardEvent): Promise<void> {
    const e = event || window.event;
    //  回车触发搜索
    if (e && e.code === 'Enter') {
      await this.onSearchButtonClick();
    }
  }
}
